﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using DongFangGuoKai.WCSPlatform.WebApi.Utils;
using Newtonsoft.Json;
using System.Security.Claims;
using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using System.Net;

namespace DongFangGuoKai.WCSPlatform.WebApi.Filter
{
    /// <summary>
    /// Action过滤器
    /// </summary>
    public class GlobalActionFilter : IActionFilter
    {
        public GlobalActionFilter(ILogger<GlobalActionFilter> logger)
        {
            this.logger = logger;
        }

        private readonly ILogger<GlobalActionFilter> logger;

        /// <summary>
        /// 入参
        /// </summary>
        static object inParam;

        public void OnActionExecuting(ActionExecutingContext context)
        {
            //if (IsLocalRequest(context)) return;

            var ipAddress = context.HttpContext.Connection.RemoteIpAddress;
            var path = context.HttpContext.Request.Path.ToString();
            var method=context.HttpContext.Request.Method;
            inParam = JsonConvert.SerializeObject(context.ActionArguments); // 获取入参
            if (!context.ModelState.IsValid)
            {
                var errors = context.ModelState.SelectMany(x => x.Value.Errors)
                    .Select(x => x.ErrorMessage)
                    .ToList();

                var result = new WCSApiResponse
                {
                    Code = 1,
                    Msg = string.Join(',', errors),
                    Data = false
                };
                //LogApiRequest(ipAddress, path, inParam.ToJson(), method, context.Result);
                context.Result = new JsonResult(result);
            }
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            //if (IsLocalRequest(context)) return;

            // 其他逻辑保持不变
            //var ipAddress = context.HttpContext.Connection.RemoteIpAddress;
            //var path = context.HttpContext.Request.Path.ToString();
            //var method = context.HttpContext.Request.Method;
            //LogApiRequest(ipAddress, path, inParam.ToJson(), method, context.Result);
        }
        /// <summary>
        /// /判断是否为本地调用
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private bool IsLocalRequest(FilterContext context)
        {
            var ipAddress = context.HttpContext.Connection.RemoteIpAddress;
            return IPAddress.IsLoopback(ipAddress);
        }

        private void LogApiRequest(IPAddress ipAddress, string url, string inParam, string method ,object outParam)
        {
            if (url== "/api/SupplyAGV/AgvCallback" || url== "/api/SupplyAGV/AgvExecute")
            {
                logger.LogInformation($"接口日志,IP:{ipAddress},Url:{url},入参:{inParam.ToJson()},出参:{outParam.ToJson()}");
            }
        }
    }
}
